package com.pcitc.app.dao.hibernate;


import org.springframework.security.userdetails.UsernameNotFoundException;


import com.pcitc.app.dao.TblUserDao;

import com.pcitc.app.model.TblUser;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import javax.persistence.Table;
import org.hibernate.LockMode;
import java.util.ArrayList;
import java.util.List;

/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve User objects.
 *
 * 
*/
public class TblUserDaoHibernate extends GenericDaoHibernate<TblUser, Long> implements TblUserDao{

    /**
     * Constructor that sets the entity to User.class.
     */
    public TblUserDaoHibernate() {
        super(TblUser.class);
    }

    /**
     * 获取组织机构列表
     */
    @SuppressWarnings("unchecked")
    public List<TblUser> getUserList() {
        return getHibernateTemplate().find("from TblUser u order by upper(u.username)");
    }

    /**
     * 保存用户
     */
    public void saveUser(TblUser tblUser) {
        log.debug("user's id: " + tblUser.getUserid());
        try {
        	if(tblUser.getUserid() !=null){
        		getHibernateTemplate().save(tblUser);
        		log.debug("save successful");
        	}else{
        		getHibernateTemplate().saveOrUpdate(tblUser);
        	}
        	//getHibernateTemplate().saveOrUpdate(tblUser);
        	
            // necessary to throw a DataIntegrityViolation and catch it in UserManager
//            getHibernateTemplate().flush();
//            return tblUser;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
    }
    /**
     * 更新用户
     */
    public TblUser upateUser(TblUser tblUser){
    	log.debug("user's id: " + tblUser.getUserid());
    	 try {
         	getHibernateTemplate().update(tblUser);
         	log.debug("update successful");
             // necessary to throw a DataIntegrityViolation and catch it in UserManager
             getHibernateTemplate().flush();
             return tblUser;
 		} catch (RuntimeException re) {
 			log.error("update failed", re);
 			throw re;
 		}
    }
    /**
     * �����û�������
     */
    public TblUser upateUserWithLock(TblUser tblUser,LockMode lock){
    	log.debug("user's id: " + tblUser.getUserid());
    	 try {
         	getHibernateTemplate().update(tblUser,lock);
         	log.debug("update successful");
             // necessary to throw a DataIntegrityViolation and catch it in UserManager
             getHibernateTemplate().flush();
             return tblUser;
 		} catch (RuntimeException re) {
 			log.error("update failed", re);
 			throw re;
 		}
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param tblUser the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public TblUser save(TblUser tblUser) {
        return null;
    }

    /** 
     * 根据用户名查找用户
    */
    public TblUser loadUserByUsername(String username) 
    throws UsernameNotFoundException {
    	List<TblUser> userList=new ArrayList<TblUser>();
    	userList=getHibernateTemplate().find("from TblUser user where user.username=?", username);
        if (userList == null || userList.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (TblUser) userList.get(0);
        }
    }
    /** 
     * 根据用户ID查找用户
    */
    public TblUser loadUserByUserId(Long userid){
    	   return (TblUser)getHibernateTemplate().get(TblUser.class, userid);
    	}
    /** 
     * 根据USER超找用户
    */
    public List<TblUser> findByExample(TblUser tblUser){
    	
		try {
			List<TblUser> results=getHibernateTemplate().findByExample(tblUser);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

    /** 
     * 删除用户
    */
    
    public void removeUser(TblUser tblUser) {
    	log.debug("user's id: " + tblUser.getUserid());
    	try {
    		getHibernateTemplate().delete(tblUser);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
    }
    /** 
     * 根据用户ID删除用户
    */
    public void removeUserByID(Long userid){
    	    TblUser tblUser = this.loadUserByUserId(userid);
    	    getHibernateTemplate().delete(tblUser);
	
    }
    /** 
     * 删除所有
    */
    public void removeAll(List<TblUser> tblUsers) {
    	
    	try {
    		getHibernateTemplate().deleteAll(tblUsers);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
    }
    /** 
     *检查用户名密码 返回USER
    */ 
    public TblUser checkUserPassword(String userName, String pwd) {
		String sql = "from TblUser user where user.username = ? and user.pwd = ?";
		Object[] param = new Object[]{userName, pwd};
		List<TblUser> tblUsers =getHibernateTemplate().find(sql, param);
		if(tblUsers == null || tblUsers.size() == 0){
			return null;
		}
		else{
			return (TblUser)tblUsers.get(0);
		}
	}
    /** 
     *检查用户名密码 返回Boolea值
    */ 
    public boolean isValidUser(String userName, String pwd) {
		String sql = "from TblUser user where user.username = ? and user.pwd = ?";
		Object[] param = new Object[]{userName, pwd};
		List<TblUser> tblUsers =getHibernateTemplate().find(sql, param);
		if(tblUsers == null || tblUsers.size() == 0){
			return false ;
		}
		else{
			return true;
		}
	}
    /** 
     *  修改用户密码
    */
	public boolean changePwd(Long userId, String oldPwd, String newPwd) {
		TblUser tblUser = this.loadUserByUserId(userId);
		if(!tblUser.getPwd().equals(oldPwd)){
			return false;
		}
		tblUser.setPwd(newPwd);
		this.saveUser(tblUser);
		return true;
	}
	/** 
     * 检查用户ID是否存在 返回Booleanֵ值
    */
   public boolean checkUserId(Long userid){
	   TblUser tblUser=this.loadUserByUserId(userid);
	  if (tblUser==null){
			 return false; 
	  }else{
		  return true;
	  }
   }
    /** 
     * 获取用户密码
    */
    public String getUserPassword(String username) {
        SimpleJdbcTemplate jdbcTemplate =
                new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
        Table table = AnnotationUtils.findAnnotation(TblUser.class, Table.class);
        return jdbcTemplate.queryForObject(
                "select pwd from " + table.name() + " where username=?", String.class, username);

    }
    public TblUser merge(TblUser detachedInstance) {
		try {
			TblUser result = (TblUser) getHibernateTemplate().merge(
					detachedInstance);
			return result;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachDirty(TblUser instance) {
		try {
			getHibernateTemplate().saveOrUpdate(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachClean(TblUser instance) {
		try {
			getHibernateTemplate().lock(instance,LockMode.NONE);
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
}
